package com.kyl.service.impl;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.kyl.exception.BaseException;
import com.kyl.service.WechatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author WanJl
 * @version 1.0
 * @title WechatServiceImpl
 * @description 微信服务实现类
 * @create 2025/1/13
 */
@Slf4j
@Service
public class WechatServiceImpl implements WechatService {

    // 登录
    private static final String REQUEST_URL = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code";

    // 获取token
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";

    // 获取手机号
    private static final String PHONE_REQUEST_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";

    //appId
    @Value("${kyl.wechat.appId}")
    private String appId;
    //appSecret
    @Value("${kyl.wechat.appSecret}")
    private String appSecret;


    /**
     * 获取微信的openId
     *
     * @param code
     */
    @Override
    public JSONObject getOpenId(String code) {
        //1、添加小程序端授权后的登录凭证code
        Map<String, Object> requestUrlParam = getAppConfig();
        requestUrlParam.put("js_code", code);
        //发送请求调用微信接口获取openid用户唯一标识
        String result = HttpUtil.get(REQUEST_URL, requestUrlParam);
        log.warn("发送请求调用微信接口获取openid：{}",result);
        //把收到的json数据转换成json对象
        return JSONUtil.parseObj(result);
    }

    /**
     * 封装公共参数
     *
     * @return
     */
    private Map<String, Object> getAppConfig() {
        Map<String, Object> requestUrlParam = new HashMap<>();
        requestUrlParam.put("appid", appId);
        requestUrlParam.put("secret", appSecret);
        return requestUrlParam;
    }

    /**
     * 获取微信的电话号码
     *
     * @param code
     * @return
     * @throws IOException
     */
    @Override
    public String getPhone(String code) throws IOException {
        //获取服务端调用凭证token
        String token = getToken();
        //增加请求token
        String url=PHONE_REQUEST_URL+token;
        Map<String, Object> map=new HashMap<>();
        //小程序授权之后的手机号临时凭证
        map.put("code",code);
        //发送POST请求到微信接口，获取手机号
        String result = HttpUtil.post(url, JSONUtil.toJsonStr(map));
        log.warn("发送POST请求到微信接口，获取手机号：{}",result);
        JSONObject jsonObject = JSONUtil.parseObj(result);
        if(jsonObject.getInt("errcode")!=0){
            throw new BaseException(jsonObject.getStr("errmsg"));
        }
        return jsonObject.getJSONObject("phone_info").getStr("purePhoneNumber");
    }

    /**
     * 获取服务端调用凭证token
     * @return
     */
    private String getToken() {
        Map<String, Object> requestUrlParam = getAppConfig();
        String result = HttpUtil.get(TOKEN_URL, requestUrlParam);
        log.warn("获取服务端调用凭证token：{}",result);
        JSONObject jsonObject = JSONUtil.parseObj(result);
        if(ObjectUtil.isNotEmpty(jsonObject.getInt("errcode"))){
            throw new BaseException(jsonObject.getStr("errmsg"));
        }
        return jsonObject.getStr("access_token");
    }


}
